// 获取服务供应商
function getProvider(): Promise<string> {
  return new Promise((resolve, reject) => {
    uni.getProvider({
      service: 'oauth',
      success: function (res) {
        resolve(res.provider as any) // 修复类型声明
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}

// 获取用户 code
export async function getCodeForLogin(): Promise<string> {
  try {
    const provider = await getProvider() // 异步获取服务供应商
    return new Promise((resolve, reject) => {
      uni.login({
        provider: provider as any,
        success: function (res) {
          resolve(res.code) // 确保返回结果是对象
        },
        fail: function (err) {
          reject(err)
        }
      })
    })
  } catch (error) {
    return Promise.reject(error) // 捕获并抛出错误
  }
}

// 调起支付
export async function requestUserPayment(payInfo: any): Promise<{ success: boolean; message: string }> {
  const provider = await getProvider() // 异步获取服务供应商
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      provider: provider as any,
      ...payInfo,
      success: () => {
        resolve({ success: true, message: '支付成功' })
      },
      fail: (e: any) => {
        resolve({ success: false, message: e || '支付失败' })
      }
    })
  })
}
